<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" v-show="showSearch" :inline="true">
      <el-form-item label="策略名称" prop="handleId">
        <el-select v-model="queryParams.handleId" placeholder="请选择" :style="{width: '100%'}">
          <el-option v-for="item in handleOption" :key="item.id" :label="item.handleName" :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="策略类型" prop="strategyType">
        <el-select v-model="queryParams.strategyType" placeholder="策略类型" clearable size="small">
          <el-option v-for="dict in dict.type.strategy_type"
                     :key="dict.value" :label="dict.label" :value="dict.value"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:role:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:role:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-if="false"
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:role:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getPage"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="page" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="策略名称" prop="pipelineHandleEntity.handleName" :show-overflow-tooltip="true" width="300"/>
      <el-table-column label="策略功能说明" prop="pipelineHandleEntity.handleDesc" :show-overflow-tooltip="true" width="300"/>
      <el-table-column label="策略类型" prop="strategyTypeCn" width="200"/>
      <el-table-column label="是否启用" prop="enableStatus" width="200">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.enableStatus"
            :active-value=1 :inactive-value=0
            @change="handleEnableStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope" v-if="scope.row.roleId !== 1">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:role:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:role:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getPage"
    />

    <!-- 添加或修改解析组元素顺序对话框 -->
    <el-dialog :visible.sync="open" :title="title" width="1000px" append-to-body>
      <div class="left-board">
        <el-form ref="form" :model="form" :rules="rules" size="medium" label-width="140px">
          <el-col :span="24">
            <el-form-item label="策略名称" prop="handleId">
              <el-select v-model="form.handleId" placeholder="请选择" :style="{width: '100%'}">
                <el-option v-for="item in handleOption" :key="item.id" :label="item.handleName" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="策略类型" prop="strategyType">
              <el-select v-model="form.strategyType" placeholder="策略类型" clearable size="small"
                         :style="{width: '100%'}">
                <el-option v-for="dict in dict.type.strategy_type"
                           :key="dict.value" :label="dict.label" :value="dict.value + ''"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-show="form.strategyType === '0'">
            <el-form-item label="测站类型" prop="stType">
              <el-select v-model="form.stType" placeholder="测站类型" clearable size="small"
                         @change="((val)=>{getStationList(val,'stType')})" :style="{width: '100%'}">
                <el-option v-for="dict in dict.type.st_type"
                           :key="dict.value" :label="dict.label" :value="dict.value"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-show="form.strategyType === '1'">
            <el-form-item label="所属行政区" prop="adCodeList">
              <el-cascader class="selectArea" :style="{width: '100%'}" ref="cascaderAddr" @change="addressChange"
                           :props="adDefaultParams" :options="adOptions" v-model="form.adCodeList"
                           :clearable="true"></el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-show="form.strategyType === '2'">
            <el-form-item label="所属行业类别" prop="industryType">
              <el-select v-model="form.industryType" placeholder="行业类别"
                         @change="getStationList" clearable size="small" :style="{width: '100%'}">
                <el-option v-for="dict in dict.type.industry_type"
                           :key="dict.value" :label="dict.label" :value="dict.value"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-show="form.strategyType === '3'">
            <el-form-item label="日期范围" prop="dateRange">
              <el-date-picker v-model="form.dateRange" type="daterange" align="right" unlink-panels
                              :style="{width: '100%'}"
                              range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
              </el-date-picker>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="是否启用" prop="enableStatus">
              <el-switch v-model="form.enableStatus" :active-value=1 :inactive-value=0></el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="策略顺序" prop="strategyOrder">
              <span slot="label">
                <el-tooltip content="针对同一站点配置多个策略触发优先级，策略顺序值乘以策略类型（全局:1...单站:5）。结果数字越小，优先级越高;" placement="top">
                  <i class="el-icon-question"></i>
                </el-tooltip>
                策略顺序
              </span>
              <el-input-number v-model="form.strategyOrder" placeholder="" :min="1"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="测站列表">
              <div class="st-code-div">
                <el-transfer v-model="form.stCodes" :titles="['未选中测站列表', '已选测站列表']"
                             filterable :props="transferProps" :data="allStationList"
                             :left-default-checked="leftDefaultChecked"
                             filter-placeholder="请输入测站名称" :filter-method="transferFilterMethod"/>
              </div>
            </el-form-item>
          </el-col>

        </el-form>
      </div>
      <div slot="footer">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    page,
    getRelStHandles,
    getRelStHandle,
    insertRelStHandle,
    updateRelStHandle,
    delRelStHandle
  } from "@/api/ruleengine/relsthandle";
  import {
    getAllStation
  } from "@/api/equipmentmanagement/equipment";
  import {list} from '@/api/ruleengine/case';
  import {getAdList} from '@/api/common/ad';
  import {isEmptyString} from '@/utils/emptyCheck';

  export default {
    dicts: ['strategy_type', 'st_type', 'industry_type'],
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 表格数据
        page: null,
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 表单参数
        form: {},
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          handleName: undefined,
          strategyType: undefined,
          pipelineHandleEntity: {}
        },
        dialogType: "",
        // 表单校验
        rules: {
          strategyId: [{
            required: true,
            message: '请选择规则策略',
            trigger: 'blur'
          }],
          strategyType: [{
            required: true,
            message: '请选择策略类型',
            trigger: 'blur'
          }],
        },
        handleOption: [],
        adOptions: [],
        adDefaultParams: {
          checkStrictly: true,
          label: 'adName',
          value: 'adCode',
          children: 'children'
        },
        dateRange: {},
        allStationList: [],
        transferProps: {
          key: 'stCd',
          label: 'stName'
        },
        // stInfoConfigEntity: {
        //   industryType: undefined,
        //   stType: undefined,
        //   adCode: undefined
        // },
        leftDefaultChecked: []
      };

    },
    created() {
      this.getPage();
      this.getStrategyList();
      this.adList();
      this.getAllStation();
    },

    methods: {
      /** 查询分页列表 */
      getPage() {
        this.loading = true;
        page(this.queryParams).then(response => {
            this.page = response.rows;
            this.total = response.total;
            this.loading = false;
          }
        );
      },
      getStrategyList() {
        this.loading = true;
        list().then(response => {
            this.handleOption = response.data;
            this.loading = false;
          }
        );
      },
      /** 查询所有接入测站列表 */
      getAllStation() {
        getAllStation().then(response => {
          this.allStationList = response.data;
        });
      },
      /** 根据查询条件查询接入测站列表 */
      getStationList(val, field) {
        let stInfoConfigEntity = {};
        stInfoConfigEntity[field] = val;
        getAllStation(stInfoConfigEntity).then(response => {
          let stationList = response.data;
          this.leftDefaultChecked = [];
          for (const item of stationList) {
            this.leftDefaultChecked.push(item.stCd);
          }
        });
      },
      // 获取行政区数据
      adList() {
        getAdList().then(response => {
          this.adOptions = response.data
        });
      },
      transferFilterMethod(query, item) {
        const stName = item.stName;
        if (stName !== null && stName !== '' && typeof(stName) !== 'undefined') {
          return item.stName.indexOf(query) > -1;
        }
        return 0;
      },
      adCodeCallBack(adCode) {
        if (adCode !== "" && adCode !== null) {
          let adCodeList = [];
          if (adCode.endsWith("0000")) {
            adCodeList.push(adCode.substring(0, 6));
          } else if (adCode.endsWith("00")) {
            adCodeList.push(adCode.substring(0, 2) + "0000");
            adCodeList.push(adCode.substring(0, 6));
          } else {
            adCodeList.push(adCode.substring(0, 2) + "0000");
            adCodeList.push(adCode.substring(0, 4) + "00");
            adCodeList.push(adCode.substring(0, 6));
          }
          this.form.adCodeList = adCodeList;
        }
      },
      /** 从省市县行政区编码数组中提取最详细的一个行政区编码 */
      adCodesToString(adCodeList) {
        if (adCodeList !== null && adCodeList !== '' && typeof (adCodeList) !== 'undefined') {
          return adCodeList[adCodeList.length - 1];
        }
      },
      addressChange(value) {
        if (!isEmptyString(value)) {
          this.getStationList(value.join(), 'adCode');
        }
      },
      // 测站锁定状态修改
      handleEnableStatusChange(row) {
        let text = row.enableStatus === 1 ? "启用" : "不启用";
        this.$modal.confirm('确认要"' + text + '""' + row.pipelineHandleEntity.handleName + '"吗？')
          .then(function () {
            return updateRelStHandle(row);
          }).then(() => {
          this.$modal.msgSuccess(text + "成功");
        }).catch(function () {
          row.enableStatus = row.enableStatus === 0 ? 1 : 0;
        });
      },

      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id);
        this.single = selection.length !== 1;
        this.multiple = !selection.length
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          handleId: undefined,
          strategyType: undefined,
          stType: undefined,
          industryType: undefined,
          adCodeList: undefined,
          dateRange: undefined,
          stCodes: [],
          enableStatus: 1,
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getPage();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.title = "新增策略配置";
        this.open = true;
        this.dialogType = "add";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const id = row.id || this.ids;
        getRelStHandle(id).then(response => {
          const data = response.data;
          this.form = data;
          this.open = true;
          this.title = "修改策略配置";
          this.dialogType = "update";
          if (!isEmptyString(data.stCode)) {
            this.form.stCodes = data.stCode.split(",");
          }
          if (!isEmptyString(data.beginDay) && !isEmptyString(data.endDay)) {
            this.form.dateRange = [];
            this.form.dateRange.push(data.beginDay, data.endDay)
          }
          this.adCodeCallBack(data.adCode);
        });
      },
      /** 提交按钮 */
      submitForm: function () {
        let that = this;
        that.$refs["form"].validate(valid => {
          if (valid) {
            that.form.adCode = this.adCodesToString(that.form.adCodeList);
            const stCodes = that.form.stCodes;
            if (stCodes !== null && stCodes !== '' && typeof (stCodes) !== 'undefined') {
              that.form.stCode = stCodes.join(',');
            }
            const dateRange = that.form.dateRange;
            if (dateRange !== null && dateRange !== '' && typeof (dateRange) !== 'undefined') {
              that.form.beginDay = dateRange[0];
              that.form.endDay = dateRange[1];
            }
            if ('update' === that.dialogType) {
              updateRelStHandle(that.form).then(response => {
                that.$modal.msgSuccess("修改成功");
                that.open = false;
                that.getPage();
              });
            } else {
              insertRelStHandle(that.form).then(response => {
                that.$modal.msgSuccess("新增成功");
                that.open = false;
                that.getPage();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const id = row.id || this.ids;
        this.$modal.confirm('是否确认删除？').then(function () {
          return delRelStHandle(id);
        }).then(() => {
          this.getPage();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {
        });
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('system/user/export', {
          ...this.queryParams
        }, `user_${new Date().getTime()}.xlsx`)
      },
    }
  };
</script>
<style lang='scss' scoped="scoped">
  .st-code-div {
    overflow-y: auto;
  }

  .el-transfer {
    width: 100%;
    ::v-deep .el-transfer-panel {
      width: 37%;
      height: 100%;
    }
  }

</style>
